/**
 * Web Vitals性能监控
 * Story 4: Task 7 - 性能监控集成
 */
import { onCLS, onFID, onLCP, onFCP, onTTFB, onINP, Metric } from 'web-vitals'

interface AnalyticsData {
  metric_name: string
  metric_value: number
  metric_rating: string
  metric_delta: number
  metric_id: string
  page_url: string
  user_agent: string
  connection_type?: string
}

/**
 * 发送性能指标到后端分析服务
 */
const sendToAnalytics = (metric: Metric) => {
  const data: AnalyticsData = {
    metric_name: metric.name,
    metric_value: metric.value,
    metric_rating: metric.rating,
    metric_delta: metric.delta,
    metric_id: metric.id,
    page_url: window.location.pathname,
    user_agent: navigator.userAgent,
  }

  // 获取网络类型（仅支持部分浏览器）
  if ('connection' in navigator) {
    const conn = (navigator as any).connection
    data.connection_type = conn?.effectiveType || conn?.type
  }

  // 在开发环境下打印到控制台
  if (import.meta.env.DEV) {
    console.log(`📊 [Web Vitals] ${metric.name}:`, {
      value: `${metric.value.toFixed(2)}ms`,
      rating: metric.rating,
      delta: `${metric.delta.toFixed(2)}ms`,
    })
  }

  // 发送到后端API（可以根据需要启用）
  if (import.meta.env.VITE_ENABLE_ANALYTICS === 'true') {
    fetch('/api/v1/analytics/web-vitals', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
      // 使用 keepalive 确保即使页面关闭也能发送
      keepalive: true,
    }).catch((error) => {
      console.error('Failed to send Web Vitals:', error)
    })
  }

  // 发送到 Google Analytics（如果有）
  if (window.gtag) {
    window.gtag('event', metric.name, {
      value: Math.round(metric.value),
      metric_id: metric.id,
      metric_value: metric.value,
      metric_delta: metric.delta,
      metric_rating: metric.rating,
    })
  }
}

/**
 * 初始化Web Vitals性能监控
 */
export const initWebVitalsMonitoring = () => {
  // Largest Contentful Paint (LCP)
  // 衡量加载性能：良好 < 2.5s, 需改进 2.5-4s, 差 > 4s
  onLCP(sendToAnalytics, { reportAllChanges: false })

  // First Input Delay (FID)
  // 衡量交互性：良好 < 100ms, 需改进 100-300ms, 差 > 300ms
  onFID(sendToAnalytics)

  // Interaction to Next Paint (INP) - FID的替代指标
  // 衡量整体交互响应性：良好 < 200ms, 需改进 200-500ms, 差 > 500ms
  onINP(sendToAnalytics, { reportAllChanges: false })

  // Cumulative Layout Shift (CLS)
  // 衡量视觉稳定性：良好 < 0.1, 需改进 0.1-0.25, 差 > 0.25
  onCLS(sendToAnalytics, { reportAllChanges: false })

  // First Contentful Paint (FCP)
  // 衡量首次内容绘制：良好 < 1.8s, 需改进 1.8-3s, 差 > 3s
  onFCP(sendToAnalytics, { reportAllChanges: false })

  // Time to First Byte (TTFB)
  // 衡量服务器响应时间：良好 < 800ms, 需改进 800-1800ms, 差 > 1800ms
  onTTFB(sendToAnalytics, { reportAllChanges: false })
}

/**
 * 获取性能评级的颜色
 */
export const getRatingColor = (rating: string): string => {
  switch (rating) {
    case 'good':
      return '#0cce6b'
    case 'needs-improvement':
      return '#ffa400'
    case 'poor':
      return '#ff4e42'
    default:
      return '#666'
  }
}

/**
 * 格式化性能指标值
 */
export const formatMetricValue = (name: string, value: number): string => {
  // CLS 没有单位
  if (name === 'CLS') {
    return value.toFixed(3)
  }
  // 其他指标都是时间（毫秒）
  return `${value.toFixed(2)}ms`
}

/**
 * 获取性能指标的阈值
 */
export const getMetricThresholds = (
  name: string
): { good: number; poor: number } => {
  const thresholds: Record<string, { good: number; poor: number }> = {
    LCP: { good: 2500, poor: 4000 },
    FID: { good: 100, poor: 300 },
    INP: { good: 200, poor: 500 },
    CLS: { good: 0.1, poor: 0.25 },
    FCP: { good: 1800, poor: 3000 },
    TTFB: { good: 800, poor: 1800 },
  }

  return thresholds[name] || { good: 0, poor: 0 }
}

// 扩展 window 类型
declare global {
  interface Window {
    gtag?: (...args: any[]) => void
  }
}
